package com.youkeyi.ddy.cloud.basic.hr.approval.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youkeyi.ddy.cloud.basic.hr.approval.entity.TblApprovalInstance;
import com.youkeyi.ddy.cloud.basic.hr.approval.entity.TblApprovalNode;
import com.youkeyi.ddy.cloud.basic.hr.approval.service.TblApprovalInstanceService;
import com.youkeyi.ddy.cloud.basic.hr.approval.service.TblApprovalNodeService;
import com.youkeyi.ddy.cloud.common.api.basic.hr.approval.instance.HrApprovalInstanceCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.hr.approval.instance.dto.HrApprovalInstanceListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.hr.approval.instance.dto.HrApprovalInstanceListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.hr.approval.instance.param.HrApprovalInstanceCreateCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.hr.approval.instance.param.HrApprovalInstanceDeleteCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.hr.approval.instance.param.HrApprovalInstanceQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.hr.approval.instance.param.HrApprovalInstanceUpdateCloudParam;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicHrConstant;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicPublicConstant;
import com.youkeyi.ddy.cloud.common.enums.ResponseCodeEnum;
import com.youkeyi.ddy.cloud.common.response.ResponseContent;
import com.youkeyi.ddy.cloud.common.utils.SimpleUUidUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 人事审批实例表 前端控制器
 * </p>
 *
 * @author xiawang.liu
 * @since 2024-05-15
 */
@Service
public class TblApprovalInstanceController implements HrApprovalInstanceCloudService {

    @Autowired
    private TblApprovalInstanceService tblApprovalInstanceService;
    @Autowired
    private TblApprovalNodeService tblApprovalNodeService;

    @Override
    public HrApprovalInstanceListCloudDto query(HrApprovalInstanceQueryCloudParam param) {
        HrApprovalInstanceListCloudDto dto = new HrApprovalInstanceListCloudDto();
        if (null == param) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        if (CollectionUtils.isNotEmpty(param.getApprovalInstancePrimaryKeys())) {
            param.getApprovalInstancePrimaryKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getCorpKeys())) {
            param.getCorpKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getApprovalTypes())) {
            param.getApprovalTypes().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getBusinessKeys())) {
            param.getBusinessKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getBusinessTypes())) {
            param.getBusinessTypes().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getCreateUserKeys())) {
            param.getCreateUserKeys().removeAll(Collections.singleton(null));
        }

        QueryWrapper<TblApprovalInstance> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .in(CollectionUtils.isNotEmpty(param.getApprovalInstancePrimaryKeys()), TblApprovalInstance::getPrimaryKey, param.getApprovalInstancePrimaryKeys())
                .in(CollectionUtils.isNotEmpty(param.getCorpKeys()), TblApprovalInstance::getCorpKey, param.getCorpKeys())
                .in(CollectionUtils.isNotEmpty(param.getApprovalTypes()), TblApprovalInstance::getApprovalType, param.getApprovalTypes())
                .in(CollectionUtils.isNotEmpty(param.getBusinessTypes()), TblApprovalInstance::getBusinessType, param.getBusinessTypes())
                .in(CollectionUtils.isNotEmpty(param.getBusinessKeys()), TblApprovalInstance::getBusinessKey, param.getBusinessKeys())
                .in(CollectionUtils.isNotEmpty(param.getCreateUserKeys()), TblApprovalInstance::getCreateUserKey, param.getCreateUserKeys())
                .like(StringUtils.isNotBlank(param.getKeyword()), TblApprovalInstance::getFormJsonStr, param.getKeyword())
                .ne(TblApprovalInstance::getIsDeleted, YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value())
        ;

        Page<TblApprovalInstance> page = new Page<>();
        if (null != param.getCurrentPage() && null != param.getPageSize()) {
            page.setCurrent(param.getCurrentPage());
            page.setSize(param.getPageSize());
        } else {
            page.setCurrent(1);
            page.setSize(99999999);
        }
        Page<TblApprovalInstance> instanceList = tblApprovalInstanceService.page(page, wrapper);
        if (CollectionUtils.isNotEmpty(instanceList.getRecords())) {
            dto.setTotal(instanceList.getTotal());

            List<HrApprovalInstanceListItemCloudDto> items = new ArrayList<>();
            instanceList.getRecords().forEach(instance -> {
                HrApprovalInstanceListItemCloudDto item = new HrApprovalInstanceListItemCloudDto();
                item.setApprovalInstancePrimaryKey(instance.getPrimaryKey());
                item.setCorpKey(instance.getCorpKey());
                item.setApprovalType(instance.getApprovalType());
                item.setApprovalTypeName(YoukeyiDdyCloudBasicHrConstant.HR_APPROVAL_TYPE.getName(instance.getApprovalType()));
                item.setFormJsonStr(instance.getFormJsonStr());
                item.setBusinessKey(instance.getBusinessKey());
                item.setBusinessType(instance.getBusinessType());
                item.setBusinessTypeName(YoukeyiDdyCloudBasicHrConstant.HR_APPROVAL_BUSINESS_TYPE.getName(instance.getBusinessKey()));
                item.setApproverApproverKey(instance.getApproverApproverKey());
                item.setApproverCcKey(instance.getApproverCcKey());
                item.setApproverKey(instance.getApproverKey());
                item.setApprover(instance.getApprover());
                item.setApprovalTime(instance.getApprovalTime() != null ? instance.getApprovalTime().getTime() : null);
                item.setApprovalResult(instance.getApprovalResult());
                item.setApprovalComment(instance.getApprovalComment());
                item.setRemarks(instance.getRemarks());
                item.setRemarks(instance.getRemarks());
                item.setIsDeleted(instance.getIsDeleted());
                item.setIsDeletedName(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO.getName(item.getIsDeleted()));
                item.setCreateTime(instance.getCreateTime() != null ? instance.getCreateTime().getTime() : null);
                item.setCreateUserKey(instance.getCreateUserKey());
                item.setCreateUserName(instance.getCreateUserName());
                item.setUpdateTime(instance.getUpdateTime() != null ? instance.getUpdateTime().getTime() : null);
                item.setUpdateUserKey(instance.getUpdateUserKey());
                item.setUpdateUserName(instance.getUpdateUserName());
                items.add(item);
            });
            dto.setRows(items);
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    @Override
    public ResponseContent create(HrApprovalInstanceCreateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || StringUtils.isBlank(param.getApprovalType())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        TblApprovalInstance instance = new TblApprovalInstance();
        instance.setPrimaryKey(SimpleUUidUtils.getUuid());
        instance.setCorpKey(param.getCorpKey());
        instance.setApprovalType(param.getApprovalType());
        instance.setFormJsonStr(param.getFormJsonStr());
        instance.setBusinessKey(param.getBusinessKey());
        instance.setBusinessType(param.getBusinessType());
        instance.setApproverApproverKey(param.getApproverApproverKey());
        instance.setApproverCcKey(param.getApproverCcKey());
        instance.setApproverKey(param.getApproverKey());
        instance.setApprover(param.getApprover());
        instance.setApprovalTime(param.getApprovalTime() != null ? new Date(param.getApprovalTime()) : null);
        instance.setApprovalResult(param.getApprovalResult());
        instance.setApprovalComment(param.getApprovalComment());
        instance.setRemarks(param.getRemarks());
        instance.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_NO.value());
        instance.setCreateUserKey(param.getCreateUserKey());
        instance.setCreateUserName(param.getCreateUserName());
        instance.setCreateTime(new Date());
        boolean save = tblApprovalInstanceService.save(instance);
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
        } else {
            // 创建节点信息
            if (CollectionUtils.isNotEmpty(param.getNodes())) {
                List<TblApprovalNode> saveNodes = new ArrayList<>();
                param.getNodes().forEach(nodeParam -> {
                    TblApprovalNode node = new TblApprovalNode();
                    node.setPrimaryKey(StringUtils.isBlank(nodeParam.getApprovalNodePrimaryKey()) ? SimpleUUidUtils.getUuid() : nodeParam.getApprovalNodePrimaryKey());
                    node.setCorpKey(instance.getCorpKey());
                    node.setInstanceKey(instance.getPrimaryKey());
                    node.setFormJsonStr(instance.getFormJsonStr());
                    node.setNodeType(nodeParam.getNodeType());
                    node.setSequence(nodeParam.getSequence());
                    node.setApproverKey(nodeParam.getApproverKey());
                    node.setSuperiorNode(nodeParam.getSuperiorNode());
                    node.setSubordinateNode(nodeParam.getSubordinateNode());
                    node.setRemarks(nodeParam.getRemarks());
                    node.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_NO.value());
                    node.setCreateUserKey(param.getCreateUserKey());
                    node.setCreateUserName(param.getCreateUserName());
                    node.setCreateTime(new Date());
                    saveNodes.add(node);
                });
                if (CollectionUtils.isNotEmpty(saveNodes)) {
                    tblApprovalNodeService.saveBatch(saveNodes);
                }
            }

            rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
            rc.setKey(instance.getPrimaryKey());
        }
        return rc;
    }

    @Override
    public ResponseContent update(HrApprovalInstanceUpdateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || StringUtils.isBlank(param.getApprovalInstancePrimaryKey())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }

        UpdateWrapper<TblApprovalInstance> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(TblApprovalInstance::getPrimaryKey, param.getApprovalInstancePrimaryKey());
        TblApprovalInstance instance = new TblApprovalInstance();
        instance.setPrimaryKey(param.getApprovalInstancePrimaryKey());
        instance.setApprovalType(param.getApprovalType());
        instance.setFormJsonStr(param.getFormJsonStr());
        instance.setBusinessKey(param.getBusinessKey());
        instance.setBusinessType(param.getBusinessType());
        instance.setApproverApproverKey(param.getApproverApproverKey());
        instance.setApproverCcKey(param.getApproverCcKey());
        instance.setApproverKey(param.getApproverKey());
        instance.setApprover(param.getApprover());
        instance.setApprovalTime(param.getApprovalTime() != null ? new Date(param.getApprovalTime()) : null);
        instance.setApprovalResult(param.getApprovalResult());
        instance.setApprovalComment(param.getApprovalComment());
        instance.setRemarks(param.getRemarks());
        instance.setUpdateUserKey(param.getUpdateUserKey());
        instance.setUpdateUserName(param.getUpdateUserName());
        instance.setUpdateTime(new Date());
        boolean save = tblApprovalInstanceService.update(instance, wrapper);
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
            return rc;
        }
        return rc;
    }

    @Override
    @Transactional
    public ResponseContent delete(HrApprovalInstanceDeleteCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || CollectionUtils.isEmpty(param.getApprovalInstancePrimaryKeys())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        UpdateWrapper<TblApprovalInstance> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .in(TblApprovalInstance::getPrimaryKey, param.getApprovalInstancePrimaryKeys());

        TblApprovalInstance instance = new TblApprovalInstance();
        instance.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value());
        instance.setUpdateUserKey(param.getUpdateUserKey());
        instance.setUpdateUserName(param.getUpdateUserName());
        instance.setUpdateTime(new Date());
        boolean save = tblApprovalInstanceService.update(instance, wrapper);
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
        } else {
            // 同步删除审批节点
            UpdateWrapper<TblApprovalNode> nodeWrapper = new UpdateWrapper<>();
            nodeWrapper.lambda()
                    .in(TblApprovalNode::getInstanceKey, param.getApprovalInstancePrimaryKeys());

            TblApprovalNode node = new TblApprovalNode();
            node.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value());
            node.setUpdateUserKey(param.getUpdateUserKey());
            node.setUpdateUserName(param.getUpdateUserName());
            node.setUpdateTime(new Date());
            tblApprovalNodeService.update(node, nodeWrapper);

            rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        }
        return rc;
    }
}
